/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.lis.model;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;

/**
 *
 * @author chuoxi
 */
public class SqlserverMetaBuilder extends MetaBuilder {

    //是否将不带前缀的表，加入的生成队列   默认true,就是所有表都会自动生成
    private boolean flag = true;
    private List<String> list = new ArrayList<String>();

    public SqlserverMetaBuilder(DataSource dataSource) {
        super(dataSource);
    }

    public SqlserverMetaBuilder(DataSource dataSource, List<String> list) {
        super(dataSource);
        this.list = list;
    }

    protected void buildTableNames(List<TableMeta> ret) throws SQLException {
        ResultSet rs = dbMeta.getTables(conn.getCatalog(), null, null, new String[]{"TABLE", "VIEW"});
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            System.out.println(tableName);
            if (excludedTables.contains(tableName)) {
                System.out.println("Skip excluded table :" + tableName);
            } else {
                TableMeta tableMeta = new TableMeta();
                tableMeta.name = tableName;
                tableMeta.remarks = rs.getString("REMARKS");

                boolean tempFlag = false;
// 移除表名前缀仅用于生成 modelName、baseModelName。tableMeta.name 表名自身不受影响
                if (removedTableNamePrefixes != null) {
                    for (String prefix : removedTableNamePrefixes) {
                        if (tableName.startsWith(prefix)) {
                            tableName = tableName.replaceFirst(prefix, "");
                            tempFlag = true;
                            break;
                        }
                    }
                }
                if (list.contains(tableName)) {
                    tableMeta.modelName = StrKit.firstCharToUpperCase(StrKit.toCamelCase(tableName));
                    tableMeta.baseModelName = "Base" + tableMeta.modelName;
                    ret.add(tableMeta);
                }
//                if (flag || tempFlag) {
//                    tableMeta.modelName = StrKit.firstCharToUpperCase(StrKit.toCamelCase(tableName));
//                    tableMeta.baseModelName = "Base" + tableMeta.modelName;
//                    ret.add(tableMeta);
//                }
            }
        }
        rs.close();
    }
    
    public List<TableMeta> build() {
		System.out.println("Build TableMeta ...");
		try {
			conn = dataSource.getConnection();
			dbMeta = conn.getMetaData();
			
			List<TableMeta> ret = new ArrayList<TableMeta>();
			buildTableNames(ret);
			for (TableMeta tableMeta : ret) {
				buildPrimaryKey(tableMeta);
				buildColumnMetas(tableMeta);
			}
			return ret;
		}
		catch (SQLException e) {
                         e.printStackTrace();
			throw new RuntimeException(e);
		}
		finally {
			if (conn != null)
				try {conn.close();} catch (SQLException e) {throw new RuntimeException(e);}
		}
	}
    
    protected void buildColumnMetas(TableMeta tableMeta) throws SQLException {
		String sql = dialect.forTableBuilderDoBuild(tableMeta.name);
                sql=sql.replace("`", "");
                System.out.println(sql);
		Statement stm = conn.createStatement();
		ResultSet rs = stm.executeQuery(sql);
		ResultSetMetaData rsmd = rs.getMetaData();
		
		for (int i=1; i<=rsmd.getColumnCount(); i++) {
			ColumnMeta cm = new ColumnMeta();
			cm.name = rsmd.getColumnName(i);
			
			String colClassName = rsmd.getColumnClassName(i);
			String typeStr = typeMapping.getType(colClassName);
			if (typeStr != null) {
				cm.javaType = typeStr;
			}
			else {
				int type = rsmd.getColumnType(i);
				if (type == Types.BINARY || type == Types.VARBINARY || type == Types.BLOB) {
					cm.javaType = "byte[]";
				}
				else if (type == Types.CLOB || type == Types.NCLOB) {
					cm.javaType = "java.lang.String";
				}
				else {
					cm.javaType = "java.lang.String";
				}
			}
			
			// 鏋勯�犲瓧娈靛搴旂殑灞炴�у悕 attrName
			cm.attrName = buildAttrName(cm.name);
			
			tableMeta.columnMetas.add(cm);
		}
		
		rs.close();
		stm.close();
	}
}
